#!/bin/sh /etc/rc.common

START=55

pctl_add_rule() {
        local cfg="$1"
        local rules="$2"
        local prefix="$3"
        local suffix="$4"
        local srcmac weekdays starttime stoptime range

        config_get srcmac $cfg src_mac
        config_get weekdays $cfg weekdays
        config_get starttime $cfg start_time
        config_get stoptime $cfg stop_time

        #echo "$srcmac $weekdays $starttime $stoptime"

        if [ -z "$srcmac" ]; then
                return 1
        fi

        append $rules "$prefix" "$N"

        append $rules "-m mac --mac-source $srcmac"

        if [ -n "$weekdays" ]; then
                append range "--weekdays $weekdays"
        fi

        if [ -n "$starttime" ]; then
                append range "--timestart $starttime"
        fi

        if [ -n "$stoptime" ]; then
                append range "--timestop $stoptime"
        fi

        if [ -n "$range" ]; then
                append $rules "-m time --kerneltz"
                append $rules "$range"
        fi

        #echo "$range"

        append $rules "$suffix"
}

start_firewall() {
        config_load parentctl
        config_get_bool pctl_enable config enabled 0

        if [ "$pctl_enable" != "1" ]; then
                stop_firewall
                return
        fi

        local pctl_rules
        local prefix="iptables -t filter -w -A parent_control"
        local suffix="-j REJECT"
        config_foreach pctl_add_rule rule pctl_rules "$prefix" "$suffix"


        stop_firewall
cat << EOF
iptables -t filter -w -N parent_control
iptables -t filter -w -I FORWARD -j parent_control
$pctl_rules
EOF
}

stop_firewall() {
        iptables -t filter -S |
                grep '\-j parent_control' |
                sed -e 's/^-A/iptables -t filter -w -D/' | sh
        iptables -t filter -S |
                grep '^-N parent_control' |
                sed -e '/^-N/{s/^-N/-X/;H;s/-X/-F/}' -e '${p;g}' |
                sed -n -e 's/^./iptables -t filter &/p' | sh
}

start() {
        start_firewall | sh
}

stop() {
        stop_firewall
}

boot() {
        start_firewall | sh
}
